var resClass = require('restaurantClass')
var login = require('login')//require('./frontend_services/login')
var coins = require('coins')//require('./frontend_services/coins')
var restaurant = require('restaurants')//require('./frontend_services/restaurants')
var chefTypes = require('chefTypes')//require('./frontend_services/chefTypes')
//定义全局用户数据格式。
var COMMON_VALUE = require('Common')
var resType = COMMON_VALUE.RESTAURANT_TYPE
let customers = require('customers')
let CUSTOMER_DATA = require('CustomerData')

var rd = new Object()
rd.recipeID = "0001"
rd.level = 1
rd.name = "宫保鸡丁"
rd.recipeEffect = new Object()
rd.recipeEffect.gainBase = 1
rd.recipeEffect.gainMultiply = 1
rd.recipeEffect.costBaseNumber = 1.07
rd.recipeEffect.costMultiply = 1
rd.recipeEffect.target = "red"

export default {
    state: {//远程获取的数据
        currentMoney: 0,
        currentReputation: 0,
        buildingGrade: 0,//建筑等级，第几座大楼
        rebornNumber: 0,//卖掉大楼的次数        
        restaurantList: [],//
        customerList: [],
        recipeDataList: [rd],//食谱数据

        //增益列表
        /*moneyBuyListOrder:0,
        moneyBuffList:[],
        reputationBuyListOrder:0,
        reputationBuffList:[],*/
        /*
        recipeData{
            recipeID:"0001",
            level:1,
            name:"宫保鸡丁"
            recipeEffect:{  gain = gainBase+level*gainMultiply; cost = costMultiply * costBaseNumber ^ level
                gainBase:1
                gainMultiply:1,
                costBaseNumber:1.07,       
                costMultiply:1,
                target:"red","yellow","blue","BARBECUE","JPFOOD"
            }
        }
        */
    },
    runtimeState: {
        connectionRetryTimes: 0,
        sellBuildingCoolDown: 0,
        UnitType: "CODE",//"SCI","FULL"数值单位的表示方法
        muteSound: true,
        muteMusic: true,
        multiplyTimes: 1,
        OverTime: false,
        gravity: cc.v2(0, -30),
        HideScreen: false,
        chefTypeList: [],
        GainMultiplyList: [],//
        buttonUpdateList: [],//[[func,node],[func,node],[func,node]...]
        chefStatusPrefabList: [],
        day: true,//是否是白天
        userSkillsCoolDownList: { earthquake: 0, fortunecat: 0, overtime: 0 },
        GPSList: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        totalGPS: 0,
        updateGPS(totalMoney) {
            let tmpGPS = 0
            for (let i = 0; i < this.GPSList.length; i++) {
                tmpGPS += this.GPSList[i]
            }
            //console.log(tmpGPS,this.totalGPS)
            if (tmpGPS != this.totalGPS && (tmpGPS || tmpGPS === 0)) {
                this.totalGPS = tmpGPS
                var kvDataList = []
                let score = JSON.stringify({
                    "wxgame": {
                        "score": this.totalGPS,
                        "update_time": Date.now()
                    },
                    "uploadedCoin": totalMoney
                })
                kvDataList.push({ "key": "score", "value": score })

                try {
                    wx.setUserCloudStorage(
                        {
                            KVDataList: kvDataList,
                            success: function (res) { cc.log(res) },
                            fail: function (res) { cc.log(res) },
                            complete: function (res) { cc.log(res) },
                        })
                } catch (err) {
                    //cc.log(err)
                }
            }
        },
        //陀螺仪系统
        GyroscopeFunctionList: [],//[[funtion,this]]
        GyroscopeChangeCallBack(GyroscopeDiffer) {
            //if(Math.sqrt(Math.pow(GyroscopeDiffer.x,2) + Math.pow(GyroscopeDiffer.y,2))>0.002){
            if (!this.HideScreen) {
                let func = null
                let self = null
                for (let i = 0; i < this.GyroscopeFunctionList.length; i++) {
                    func = this.GyroscopeFunctionList[i][0]
                    self = this.GyroscopeFunctionList[i][1]
                    func(self, GyroscopeDiffer)
                }
            }
        }
    },

    updateSkill(chefData) {
        //已学会技能
        for (var i = 0; i < chefData.skillList.length; i++) {
            if (chefData.skillList[i].levelGet <= chefData.level && !this._skillIsInArray(chefData.skillLearnt, chefData.skillList[i])) {
                chefData.skillLearnt.push(chefData.skillList[i])
            }
        }
        for (var i = 0; i < chefData.skillLearnt.length; i++) {
            if (!this._skillIsInArray(this.runtimeState.GainMultiplyList, chefData.skillLearnt[i])) {
                this.runtimeState.GainMultiplyList.push(chefData.skillLearnt[i])//更新已学会的技能
            }
        }
        return chefData.skillLearnt
    },

    _skillIsInArray(array, skill) {
        for (var i = 0; i < array.length; i++) {
            if (array[i].skillID) {
                if (skill.skillID === array[i].skillID) {
                    return true
                }
            }
        }
        return false
    },
    handleOffline() {
        this.runtimeState.offlinePromptNode.active = true
        this.CCdirector.loadScene('Loading')
    },
    updateButtonList() {
        let func = null
        let node = null
        let availableNum = 0
        let totalNum = this.runtimeState.buttonUpdateList.length
        for (var i = 0; i < this.runtimeState.buttonUpdateList.length; i++) {
            func = this.runtimeState.buttonUpdateList[i][0]
            node = this.runtimeState.buttonUpdateList[i][1]
            if (func(node)) {
                availableNum += 1
            }
        }
        if (availableNum < 4) {
            //cc.log(availableNum/totalNum)
        }
    },
    getReputation() {
        return this.state.currentReputation
    },
    setReputation(num) {
        if (typeof (num) == "number") {
            this.state.currentReputation = num
        }
    },
    addReputation(num) {
        if (typeof (num) == "number") {
            this.state.currentReputation += num
        }
    },
    subReputation(num) {
        if (typeof (num) == "number") {
            this.state.currentReputation -= num
        }
    },
    setCurrentMoney(num) {
        if (typeof (num) == "number") {
            this.state.currentMoney = num
        }
        this.updateButtonList()
    },
    getCurrentMoney() {
        return this.state.currentMoney
    },
    addCurrentMoney(num) {
        if (typeof (num) == "number") {
            this.state.currentMoney += num
            this.updateRemoteMoney(num)
        }
        this.updateButtonList()
        try{
            if(this.getCurrentMoney()>=500 &&this.runtimeState.tutorialProgress){
                if(!this.runtimeState.tutorialProgress.recipeNode){
                    this.runtimeState.guide.guide = this.runtimeState.guide.TutorialArray.recipeNode
                    this.runtimeState.guide.next()
                }
            }
        }catch(err){

        }
        
        // 检查满足[钱]条件的顾客, 如果有发送请求获得该角色
        CUSTOMER_DATA.LIST.forEach((item) => {
            if (this.acquiredCustomersList && this.acquiredCustomersList.includes(item.id)) {
                return
            } else if (item.condition === 'money' && this.state.currentMoney > item.conditionValue) {
                // 向服务器发送添加客户id请求
                customers.appendCustomer(item.id)
            }
        })
    },
    updateRemoteMoney(num) {
        if (num > this.getCurrentMoney() / 1000) {//少量的金币不与后端同步
            coins.incCoins(num).then((coin) => {
            }).catch((err) => { //捕捉错误处理  
            })
        }
    },
    subCurrentMoney(num) {
        if (typeof (num) == "number") {
            if (this.getCurrentMoney() >= num) {
                this.state.currentMoney -= num
                this.updateButtonList()
                coins.incCoins(-num).then((coin) => {
                    if (coin.data.status != "ok") {
                        console.log('UpdateMonneyCostErr')
                    }
                }).catch(function (err) { //捕捉错误处理  
                    if (err.message != "Cannot read property 'status' of undefined") {
                        console.log(err);
                    }
                })
                return true
            } else {
                return false
            }
        }
    }
}